<template>
  <div class="role-config">
    <!-- 操作栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增角色
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedIds.length === 0"
        @click="handleBatchDelete"
      >
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        :data="roleList"
        style="width: 100%"
        v-loading="loading"
        empty-text="暂无数据"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="角色ID" width="100" />
        <el-table-column prop="name" label="角色名称" min-width="150" />
        <el-table-column prop="description" label="角色描述" min-width="200" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleEdit(scope.row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              plain
              @click="handleDelete(scope.row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
      @closed="handleDialogClosed"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入角色名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入角色描述（选填）"
          />
        </el-form-item>

        <el-form-item label="功能配置" prop="functionIds">
          <el-checkbox-group v-model="formData.functionIds">
            <el-checkbox
              v-for="func in functionList"
              :key="func.id"
              :label="func.id"
            >
              {{ func.name }}
            </el-checkbox>
          </el-checkbox-group>
          <div class="form-tip">不选则默认仅拥有基本权限</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getRoleListAPI,
  addRoleAPI,
  updateRoleAPI,
  deleteRoleAPI,
  batchDeleteRoleAPI
} from '@/api/role'
import { onMounted, ref, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { Role } from '@/types/user'

// 响应式数据
const loading = ref(false)
const roleList = ref<Role[]>([])
const selectedIds = ref<number[]>([])
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)

// 表单数据
const formRef = ref<FormInstance>()
const formData = ref<{
  id: number
  name: string
  description: string
  functionIds: number[]
  menuIds: number[]
}>({
  id: 0,
  name: '',
  description: '',
  functionIds: [],
  menuIds: []
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 功能列表配置
const functionList = [
  { id: 1, name: '用户管理' },
  { id: 2, name: '角色管理' },
  { id: 3, name: '内容管理' }
]

// 对话框标题
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑角色' : '新增角色'
})

// 页面加载时获取数据
onMounted(() => {
  getRoleList()
})

// 获取角色列表
const getRoleList = async () => {
  loading.value = true
  try {
    const { data: res } = await getRoleListAPI()
    if (res.code !== 1) {
      ElMessage.error(res.msg || '获取角色列表失败')
      return
    }
    roleList.value = res.data || []
  } catch {
    ElMessage.error('网络请求失败')
  } finally {
    loading.value = false
  }
}

// 处理表格选择变化
const handleSelectionChange = (selection: Role[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 处理新增
const handleAdd = () => {
  formData.value = {
    id: 0,
    name: '',
    description: '',
    functionIds: [],
    menuIds: []
  }
  isEdit.value = false

  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: Role) => {
  isEdit.value = true
  formData.value = {
    id: row.id,
    name: row.name,
    description: row.description || '',
    functionIds: row.functionIds || [],
    menuIds: row.menuIds || []
  }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row: Role) => {
  ElMessageBox.confirm(
    `确定要删除角色"${row.name}"吗？删除后不可恢复！`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const { data: res } = await deleteRoleAPI(row.id)
      if (res.code !== 1) {
        ElMessage.error(res.msg || '删除失败')
        return
      }
      ElMessage.success('删除成功')
      getRoleList()
    } catch {
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 个角色吗？删除后不可恢复！`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const { data: res } = await batchDeleteRoleAPI(selectedIds.value)
      if (res.code !== 1) {
        ElMessage.error(res.msg || '批量删除失败')
        return
      }
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      getRoleList()
    } catch {
      ElMessage.error('批量删除失败，请重试')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    submitLoading.value = true
    try {
      const apiFunc = isEdit.value ? updateRoleAPI : addRoleAPI
      const { data: res } = await apiFunc(formData.value)
      console.log('角色配置',res);


      if (res.code !== 1) {
        ElMessage.error(res.msg || `${isEdit.value ? '更新' : '新增'}失败`)
        return
      }

      ElMessage.success(`${isEdit.value ? '更新' : '新增'}成功`)
      dialogVisible.value = false
      getRoleList()
    } catch {
      ElMessage.error(`${isEdit.value ? '更新' : '新增'}失败，请重试`)
    } finally {
      submitLoading.value = false
    }
  })
}

// 对话框关闭时重置表单
const handleDialogClosed = () => {
  formRef.value?.resetFields()
  formData.value = {
    id: 0,
    name: '',
    description: '',
    functionIds: [],
    menuIds: []
  }
}
</script>

<style scoped>
.role-config {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 120px);
}

.toolbar {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
  display: flex;
  gap: 12px;
}

.table-section {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: 1px solid #ebeef5;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

/* 按钮样式 */
:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

/* 表单提示文字 */
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.5;
}

/* 功能配置复选框样式 */
:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

:deep(.el-checkbox) {
  margin-right: 0;
}
</style>
